<!-- 经销商后结算模块-财务管理-采购单确认收货/提交/撤销 -->
<template>
  <div class="after-settlement-change-box">
    <el-container class="change-container is-vertical">
      <record-info
        class="custom-info"
        :record-form="activeFormColumns"
        :record-data="headerInfo">
        <template slot="recordInfoslot">
          <SearchForm
            v-if="isReceive"
            label-width="120px"
            :data="purchaseSearchData"
            :compact-data="purchaseSearchData.slice(0,2)"
            show-collapse
            @searchForm="searchForm"
            @resetForm="resetForm"
            :submit-loading='tableLoading'
          />
          <div
            class="solt-info">
            <span class="left-span">
              采购产品总数
              <span class="right-span">{{ headerInfo.prodTotalCount }}</span>
            </span>
            <span>
              品种数
              <span>{{ headerInfo.prodTypeCount }}</span>
            </span>
            <span>
              金额合计 （元）:
              <span>
                <span class="price">{{ headerInfo.orderAmount | getFormatterPrice }}</span>
              </span>
            </span>
          </div>
        </template>
      </record-info>
      <el-editable
        class="hospital-edit-box"
        :data="activeList"
        :key="activeIndex"
        height="200"
        v-loading="tableLoading"
        :columns="activeColumns"
      >
        <template
          slot="default-pssProdCode"
          slot-scope="scope">
          <el-select
            v-if="isReceive"
            v-model="scope.row.pssProdCode"
            filterable
            clearable
            :filter-method="getProdList"
            @change="setProdInfo($event, scope.row)"
            @focus="getProdList(scope.row.pssProdCode)"
            placeholder="请选择">
            <el-option
              v-for="item in prodOptions"
              :key="item.companyProdCode"
              :title="item.companyProdCode"
              :label="item.companyProdCode"
              :value="item.companyProdCode"/>
          </el-select>
          <span v-else>
            {{ scope.row.pssProdCode }}
          </span>
        </template>
        <template
          slot="default-pssRegistrationNumber"
          slot-scope="scope">
          <el-button
            :disabled="!scope.row.pssRegistrationNumber||!scope.row.pssRegistrationId"
            v-html="regisNoButton(scope.row, 'pssRegistration')"
            @click="showPdfRegistion(scope.row.pssRegistrationId)"
            type="text"
          />
        </template>
        <template
          slot="default-hspRegistrationNumber"
          slot-scope="scope">
          <el-button
            :disabled="!scope.row.hspRegistrationNumber||!scope.row.hspRegistrationId"
            v-html="regisNoButton(scope.row, 'hspRegistration')"
            @click="showPdfRegistion(scope.row.hspRegistrationId)"
            type="text"
          />
        </template>
      </el-editable>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      />
    </el-container>
  </div>
</template>

<script>
import {
  distributorPurchaseConfrim,
  distributorPurchaseDetail,
  distributorPurchaseOrderOperate,
  distributorPurchaseRelation,
  distributorPurchaseItemWait,
  authItemSaleQuery,
  authItemCommonQuery,
  partnerList
} from '@const/beforeSettleApi'
import { getCertificate } from '@const/productCenterApiV2'
import {
  partOrderColumns,
  partWaitColumns,
  purcharseReceiveForm,
  purcharseSubmitForm,
  statusArr,
  purchaseSearchData
} from './const'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import RecordInfo from '@/moduleComponents/beforeSettle/distributorSide/purchasingManagement/record'
import ElEditable from '@components/el-editable'
import SearchForm from '@components/businesscomponents/search'
import { cloneDeep, isObject, hasIn } from 'lodash'
import { getFormatterPrice } from '@const/filter'
import { mapState } from 'vuex'
export default {
  components: { ElEditable, RecordInfo, SearchForm },
  data () {
    return {
      id: this.$route.query.id,
      orderStatus: null,
      // 是否入住M平台
      isInM: null,
      inMObj: {
        0: '否',
        1: '是'
      },
      purchaseSearchData,
      // 表格Loading
      tableLoading: false,
      orderLists: [],
      // 搜索返回内容
      searchData: {},
      // 表头
      columnsList: [partOrderColumns, partWaitColumns],
      formColumnsList: [purcharseSubmitForm, purcharseReceiveForm],
      // 表单 详情展示内容-table
      curPage: 1, // 当前页
      PAGE_NUMBER, // 页码数组
      PAGINATION_LAYOUT, // 页码功能布局
      pageSize: PAGE_NUMBER[0], // 一页的数量
      totalElements: 0, // 总共的条数
      // 订单详情信息
      headerInfo: {},
      prodOptions: []
    }
  },
  computed: {
    ...mapState(['companyId']),
    isWaitSubmit () {
      return [21].includes(this.orderStatus)
    },
    // 待收货
    isReceive () {
      // 订单状态（0-全部，21-待提交；22-待供应商响应；23-待供应商发货；24-待收货；25-收货完成；26-已撤消；27-已拒绝）
      return [24].includes(this.orderStatus)
    },
    activeIndex () {
      return [21, 22].includes(this.orderStatus) ? 0
        : [24].includes(this.orderStatus) ? 1
          : null
    },
    activeFormColumns () {
      return this.formColumnsList[this.activeIndex]
    },
    activeColumns () {
      return this.columnsList[this.activeIndex]
    },
    activeList () {
      return this.orderLists[this.activeIndex]
    }
  },
  mounted () {
    this.getOrderStatusById()
  },
  filters: {
    getFormatterPrice
  },
  methods: {
    // 初始化数据
    async getOrderStatusById () {
      await this.getList(0)
      this._globalBtns()
      this.getList()
    },
    _globalBtns () {
      // 订单状态（0-全部，21-待提交；22-待供应商响应；23-待供应商发货；24-待收货；25-收货完成；26-已撤消；27-已拒绝）
      // 21待提交: 撤销 提交 推送供应商
      // 22待供应响应: 撤销
      // 24待收货: 暂存 确认收货
      let arr = [21].includes(this.orderStatus) ? [
        { type: 'danger', val: '撤销', handle: this.roRevoke },
        { type: 'primary', val: '提交', handle: this.toSubmisson },
        { type: 'primary', val: '推送供应商', handle: this.toPushSupplier }
      ]
        : [22].includes(this.orderStatus) ? [{ type: 'danger', val: '撤销', handle: this.roRevoke }]
          : [24].includes(this.orderStatus) ? [
            { type: 'primary', val: '暂存', handle: this.toStorage },
            { type: 'primary', val: '确认收货', handle: this.toReceiveGoods }
          ]
            : []
      const btn = {
        type: 'btn',
        arr
      }
      this.$store.commit('changeLayoutHandle', btn)
    },
    setProdInfo (value, row) {
      let itemArr = this.prodOptions.filter(col => {
        return Object.is(col.companyProdCode, value)
      })
      let item = itemArr[0] || {}
      item = {
        authProdId: item.id,
        pssProdCode: item.companyProdCode,
        pssProdName: item.prodNameCn,
        pssProdSpecs: item.spec,
        pssProdModel: item.model,
        pssMinUnit: item.unit,
        pssRegistrationId: item.registrationId,
        pssRegistrationNumber: item.registrationNumber,
        pssManufacturer: item.manufacturer,
        pssProdBigCategory: item.bigType
      }
      Object.assign(row, item)
      // console.log(200, row)
    },
    // 获取产品信息
    async getProdList (val) {
      // 配送商ID
      const downEnterpriseId = this.companyId
      const body = {
        companyProdCode: val || '',
        page: 1,
        downEnterpriseId,
        pageSize: 20,
        authItemStatus: 2
      }
      const data = await this.$axios.$post(authItemCommonQuery, body)
      if (data.code === '0') {
        this.prodOptions = hasIn(data, 'payload.content') ? data.payload.content || []
          : []
      }
    },
    // 操作订单状态
    changeOrderStatus (operateType) {
      // operateType订单操作（1-撤销，2-提交，3-推送供应商）
      const body = {
        purchaseOrderId: this.id,
        operateType
      }
      return this.$axios.$post(distributorPurchaseOrderOperate, body)
    },
    // 撤销
    async roRevoke () {
      const data = await this.changeOrderStatus(1)
      data.code === '0' && this.$router.go(-1)
    },
    // 提交
    async toSubmisson () {
      const data = await this.changeOrderStatus(2)
      data.code === '0' && this.$router.go(-1)
    },
    // 推送供应商
    async toPushSupplier () {
      if (this.isInM === 0) {
        this.$message.warning('请先入驻M平台')
        return
      }
      const data = await this.changeOrderStatus(3)
      if (data.code === '0') {
        this.$router.go(-1)
      }
    },
    // 产品数据更新处理前置
    initProdList (isStory = false) {
      const isHasProdCode = item => item.pssProdCode || isStory
      return this.orderLists[1].filter(isHasProdCode).map(item => {
        return {
          hosProdCode: item.hspProdCode,
          orderItemId: item.orderItemId,
          authProdId: item.authProdId,
          pssProdCode: item.pssProdCode,
          pssProdName: item.pssProdName,
          pssProdSpecs: item.pssProdSpecs,
          pssProdModel: item.pssProdModel,
          pssMinUnit: item.pssMinUnit,
          pssRegistrationId: item.pssRegistrationId,
          pssRegistrationNumber: item.pssRegistrationNumber,
          pssManufacturer: item.pssManufacturer,
          pssProdBigCategory: item.pssProdBigCategory
        }
      })
    },
    // 暂存
    async toStorage () {
      const productInfoList = this.initProdList(true)
      if (!productInfoList.length) {
        this.$message.warning('先选择产品')
        return
      }
      const body = {
        purchaseOrderId: this.id,
        productInfoList
      }
      const data = await this.$axios.$post(distributorPurchaseRelation, body)
      if (data.code === '0') {
        this.getList()
      }
    },
    // 收货
    async toReceiveGoods () {
      const productInfoList = this.initProdList()
      if (productInfoList.length < this.orderLists[1].length) {
        this.$message.warning('先选择产品')
        return
      }
      const body = {
        purchaseOrderId: this.id,
        productInfoList
      }
      const data = await this.$axios.$post(distributorPurchaseConfrim, body)
      if (data.code === '0') {
        this.$router.push('/distributorSide/purchasingManagement/settlement')
      }
    },
    // 搜索功能-点击查询
    searchForm (condition) {
      this.searchData = condition
      this.getList()
    },

    // 点击重置
    resetForm (condition) {
      this.curPage = 1
      this.searchData = condition
    },
    /**
     * @param [Number] index
     * @desc 通过index选择请求方法 -- 获取--0:订单信息/1:收货信息
     */
    async getList (index = this.activeIndex) {
      if (![0, 1].includes(index)) return
      this.tableLoading = true
      // 表格字段名称 订单详情--getOrderList 发货详情--getReceiveList
      const requestList = [this.getOrderList, this.getReceiveList]
      const request = requestList[index]
      const { infoList, ...baseInfo } = await request()
      Object.keys(baseInfo).forEach(key => {
        // 处理订单状态
        if (key === 'orderStatus') {
          this.orderStatus = baseInfo[key]
          baseInfo[key] = statusArr[baseInfo[key]]
        }
        // 处理订单是否入住M平台
        if (key === 'inM') {
          this.isInM = baseInfo[key]
          baseInfo[key] = this.inMObj[baseInfo[key]]
        }
        this.$set(this.headerInfo, key, baseInfo[key] || '--')
      })
      this.tableLoading = false
      this.$set(this.orderLists, index, infoList.content)
      this.totalElements = infoList.totalElements || 0
    },
    // 详情-销售单详情
    async getOrderList (flag = this.isWaitSubmit) {
      // 表格字段名称 订单详情--purchaseProductList 发货详情--waitReceiveProductList
      const url = distributorPurchaseDetail
      const data = {
        submitFlag: flag,
        page: this.curPage,
        pageSize: this.pageSize,
        purchaseOrderId: this.id,
        ...this.searchData
      }
      const res = await this.$axios.$post(url, data)
      const { purchaseProductList, ...baseInfo } = res.payload
      return { ...baseInfo, infoList: purchaseProductList }
    },
    // 详情-代收货详情
    async getReceiveList () {
      const url = distributorPurchaseItemWait
      const data = {
        page: this.curPage,
        pageSize: this.pageSize,
        purchaseOrderId: this.id,
        ...this.searchData
      }
      const res = await this.$axios.$post(url, data)
      const { waitReceiveProductList, ...baseInfo } = res.payload
      return { ...baseInfo, infoList: waitReceiveProductList }
    },
    // 注册证
    showPdfRegistion (id) {
      this.$axios({
        method: 'get',
        url: getCertificate,
        params: {
          id: id
        }
      }).then(res => {
        let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
        let url = obj.pictureUrl
        if (!url) {
          this.$message({
            type: 'warning',
            message: '获取失败，请在产品管理中维护该产品的注册证信息'
          })
        } else {
          this.$pdfViewer({ url, title: '注册证pdf预览' })
        }
      })
    },
    regisNoButton (data, str = 'registration') {
      const number = `${str}Number`
      const id = `${str}Id`
      if (data[number]) {
        return data[number]
      } else if (!data[number] && data[id]) {
        return '暂无注册证号'
      } else if (!data[number] && !data[id]) {
        return '暂无数据'
      }
    },
    // 页码更改
    handleSizeChange (size) {
      this.pageSize = size
      this.getList()
    },
    // 切换不一样的页面,重置一切数据
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.getList()
    }
  }
}
</script>

<style lang="less">
.after-settlement-change-box {
  .change-container {
    height: 100%;
    .custom-info {
      margin: 0 0 20px 0;
    }
    .pagination {
      padding-top: 10px;
      display: flex;
      justify-content: flex-end;
      padding-right: 0;
    }
  }
}
</style>
